import {ElFormComponent, ElRuleItem} from '@/plugins/element/ElementAddType';
import {Ref} from 'vue';
import store from '@/store/index';
import {apiMethod} from '@/apis/apis';
import ccRouter from '@/router';
import {RouteNameEnum} from '@/model/RouterClass';
import {Loading, pageLoading} from '@/model/LoadingClass';
import {loadingUtil} from '@/util/LoadingUtil';

export class LoginUser {
  public userName!: string;
  public password!: string;
}

export class LoginUserFormRule {
  public userName!: ElRuleItem[];
  public password!: ElRuleItem[];
}

export class User {
  public nickName!: string;
  public realName!: string;
  public email!: string;
  public userName!: string;
  [propName: string]: any;
}

export async function submitLogin(
  loginFormUser: { userName: string; password: string },
  loginForm: ElFormComponent,
  loginLoading?: Ref<boolean> | Loading): Promise<void> {
  const data: boolean = await loginForm.validate();
  if (data) {
    loadingUtil.startLoading(loginLoading);
    const res = await apiMethod.apiUserLogin(loginFormUser, loginLoading);
    await store.dispatch('user/asyncSetToken', res.result.token);
    await store.dispatch('user/asyncSetUser', res.result.apiUser);
    loadingUtil.endLoading(loginLoading);
    await ccRouter.push({routeName: RouteNameEnum.home});
  }
}

export async function logout() {
  loadingUtil.startLoading();
  await apiMethod.apiUserLogout();
  loadingUtil.endLoading();
  await store.dispatch('user/asyncSetToken', null);
  await store.dispatch('user/asyncSetUser', null);
  await ccRouter.push({routeName: RouteNameEnum.login});
}

